package br.com.seosoft.simplecalcfinan.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Tracker;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.telephony.SmsMessage;
import android.util.Log;
import br.com.seosoft.simplecalcfinan.R;
import br.com.seosoft.simplecalcfinan.geral;
import br.com.seosoft.simplecalcfinan.inicial;
import br.com.seosoft.simplecalcfinan.bancoDados.BancoDados;

/**
 * BroadcastReceiver
 * 
 */
public class ReceberSMS extends BroadcastReceiver {

	private static final String CATEGORIA = geral.LogCat;
	protected String celular, mensagem;
	protected Context contexto;
	private SharedPreferences preference;
	private SharedPreferences.Editor editor;

	public static final String SMS_EXTRA_NAME = "pdus";
	public static final String SMS_URI = "content://sms";

	public static final String ADDRESS = "address";
	public static final String PERSON = "person";
	public static final String DATE = "date";
	public static final String READ = "read";
	public static final String STATUS = "status";
	public static final String TYPE = "type";
	public static final String BODY = "body";
	public static final String SEEN = "seen";

	public static final int MESSAGE_TYPE_INBOX = 1;
	public static final int MESSAGE_TYPE_SENT = 2;

	public static final int MESSAGE_IS_NOT_READ = 0;
	public static final int MESSAGE_IS_READ = 1;

	public static final int MESSAGE_IS_NOT_SEEN = 0;
	public static final int MESSAGE_IS_SEEN = 1;

	@Override
	public void onReceive(Context context, Intent intent) {

		preference = PreferenceManager.getDefaultSharedPreferences(context);
		editor = preference.edit();

		Log.i(CATEGORIA, ">" + intent.getAction());
		contexto = context;
		Sms sms = new Sms();
		// Ler a mensagem
		SmsMessage msg = sms.receberMensagem(intent);
		celular = msg.getDisplayOriginatingAddress();
		mensagem = msg.getDisplayMessageBody();

		// Toast.makeText(context, texto, Toast.LENGTH_LONG).show();

		// Get ContentResolver object for pushing encrypted SMS to incoming
		// folder
		ContentResolver contentResolver = context.getContentResolver();

		IBancos banco = new BancosSMS(mensagem, celular).getBanco();

		// !!!IMPORTANT verifica se SMS ������ de algum banco e se esta ok
		if (banco != null) {

			if (banco.getData() != null && banco.getDescricao() != null
					&& banco.getValor() != null) {

				execSMS(mensagem);
				abortBroadcast();
				putSmsToDatabase(contentResolver, msg);
			}

		}

	}

	// FAZ A LEITURA DO SMS
	public void execSMS(String smsMensagem) {
		new threadReceberSMS().execute(smsMensagem);
	}

	// MOSTRAR NOTIFICA������AO

	public void notificacao(String titulo, String descricao, int drawable,
			long data) {

		int dot = 200; // Length of a Morse Code "dot" in milliseconds
		int dash = 500; // Length of a Morse Code "dash" in milliseconds
		int short_gap = 200; // Length of Gap Between dots/dashes
		int medium_gap = 500; // Length of Gap Between Letters
		int long_gap = 1000; // Length of Gap Between Words

		long[] pattern = { 0, // Start immediately
				dot, short_gap, dot, short_gap, medium_gap, // s
				medium_gap

		};

		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				contexto).setSmallIcon(drawable).setContentTitle(titulo)
				.setContentText(descricao).setWhen(data).setAutoCancel(true);

		Intent intent;
		intent = new Intent(contexto, inicial.class);

		TaskStackBuilder stackBuilder = TaskStackBuilder.create(contexto);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addParentStack(inicial.class);
		// Adds the Intent that starts the Activity to the top of the stack
		stackBuilder.addNextIntent(intent);
		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
				PendingIntent.FLAG_UPDATE_CURRENT);

		mBuilder.setContentIntent(resultPendingIntent);

		if (preference.getBoolean("vibrar", true) == true) {

			mBuilder.setVibrate(pattern);
		}

		if (preference.getBoolean("som", true) == true) {

			Uri path = Uri
					.parse("android.resource://br.com.seosoft.simplecalcfinan/raw/"
							+ preference.getString("listaDeSons", "coin01"));

			mBuilder.setSound(path);
		}

		// Moves the big view style object into the notification object.

		NotificationManager mNotificationManager = (NotificationManager) contexto
				.getSystemService(Context.NOTIFICATION_SERVICE);
		int mId = 35;
		// mId allows you to update the notification later on.

		mNotificationManager.notify(mId, mBuilder.build());
	}

	// CLASS RECEBE THREAD SMS
	class threadReceberSMS extends

	AsyncTask<String, Void, IBancos> {

		String error;
		IBancos banco;
		int id;
		BancoDados bd;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub

			bd = new BancoDados(contexto,false);
			super.onPreExecute();

		}

		@Override
		protected IBancos doInBackground(String... smsMensagem) {

			banco = new BancosSMS(smsMensagem[0], celular).getBanco();
			bd.setPastaSms();
			id = bd.getPastaSMSId();

			// VERIFICA SE DEBITO OU RECEITA

			if (banco != null) {

				SimpleDateFormat formatarDataTotal = new SimpleDateFormat(
						"yyyy-MM-dd", Locale.getDefault());

				String dataFormatada = formatarDataTotal
						.format(banco.getData());

				if (banco.getDescricao() != null & banco.getValor() != null
						& banco.getData() != null) {

					bd.GravaRegistroContas(String.valueOf(id),
							banco.getDescricao(), banco.getValor().toString(),
							dataFormatada);

					return banco;

				}

			}
			return null;

		}

		@Override
		protected void onPostExecute(IBancos result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) {
				geral utils = new geral();

				notificacao(result.getDescricao(),
						utils.DecimalCurrency(result.getValor()),
						R.drawable.ic_launcher, result.getData().getTime());
			} else {
				notificacao(
						Resources.getSystem().getString(
								android.R.string.dialog_alert_title),
						"Esse SMS ainda n������o ������ suportado",
						R.drawable.ic_launcher, System.currentTimeMillis());
			}
			
			
			editor.putBoolean(result.getNomebanco(), true);
			editor.commit();

			

		}

	}

	private void putSmsToDatabase(ContentResolver contentResolver,
			SmsMessage sms) {
		// Create SMS row
		ContentValues values = new ContentValues();
		values.put(ADDRESS, sms.getOriginatingAddress());
		values.put(DATE, sms.getTimestampMillis());
		values.put(READ, MESSAGE_IS_NOT_READ);
		values.put(STATUS, sms.getStatus());
		values.put(TYPE, MESSAGE_TYPE_INBOX);
		values.put(SEEN, MESSAGE_IS_NOT_SEEN);
		values.put(BODY, sms.getMessageBody());

		// Push row into the SMS table
		contentResolver.insert(Uri.parse(SMS_URI), values);
	}

}
